#coding=utf-8

# import asyncio
import web
from agent import Ai
import json
import  collections
from bot import Bot

texas_ai = Ai()


bots = {}
train_bot_id = None
train_bot_name = "550A"
train_bot = Bot(train_bot_name)

##############################
urls = (
    '/', 'index',
    "/add", "add",
    # "/.*", "notfound",
    "/ai", "ai",
    "/game_over", "game_over",
    "/train", "train",
    "/save", "save",
)

class index:
    def GET(self):
        return "Hello, world!"

class add:
    def GET(self):
        print('--from class add')
        i = web.input()
        print('--i--',i)
        ss = ""
        num = 0
        for k in i.keys():
            print(k,i.get(k))
            ss = ss +"+"+ i.get(k)         
            num = num + int(i.get(k))
        return "" +ss + "=" + str(num)

class new:
    def POST(self):
        # texas_ai.new_game()
        return

class notfound:
    def GET(self):
        return "404 notfound!"



class ai:
    def POST(self):
        # print("ai------------------------------")
        json_str = web.data()
        # print("web_data:",json_str)
        data = json.loads(json_str)
        print("----ai:-----", data)
        state = data["state"]
        uid = data["uid"]
        action_nums = state['legal_actions']
        arr = []
        for i in action_nums:
            arr.append((int(i), None))
        state['legal_actions'] = collections.OrderedDict(arr)
        # global train_bot_id
        # if train_bot_id == None:
        #     train_bot_id = uid
            
        # if train_bot_id == uid:
        #     print("use train ai", uid)
        #     oper = train_bot.step(state)
        # else:
        #     print("use normal ai", uid)
        #     oper = texas_ai.step(state)

        print("use normal ai", uid)
        oper = texas_ai.step(state)        

        res = json.dumps({"oper" : oper,
            "code": 0
        })
        return res

class train:
    def POST(self):
        json_str = web.data()
        data = json.loads(json_str)
        print("train:", data)
        state = data["state"]
        uid = data["uid"]    
        if not(uid in bots):
            bot = Bot(uid)
            bots[uid] = bot
        action_nums = state['legal_actions']
        arr = []
        for i in action_nums:
            arr.append((int(i), None))
        state['legal_actions'] = collections.OrderedDict(arr)
        oper = bots[uid].step(state)       
        res = json.dumps({"oper" : oper,
            "code": 0
        })
        return res


class game_over:
    def POST(self):
        json_str = web.data()
        data = json.loads(json_str)
        print("game_over:", data)
        reward = data["reward"]
        uid = data["uid"]
        global train_bot_id
        if train_bot_id == uid:
            train_bot.game_over(reward)
            train_bot_id = None

        res = json.dumps({"code": 0})
        if not(uid in bots):
            print("not has uid", uid)
            return res

        bots[uid].game_over(reward)


        return res



class save:
    def POST(self):
        train_bot.save()

        json_str = web.data()
        data = json.loads(json_str)
        uid = data["uid"]
        res = json.dumps({"code": 0})
        if not(uid in bots):
            print("not has uid", uid)
            return res

        bots[uid].save()

        return res


















if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()